/**
 * Created by admin on 2017/12/11.
 */
/**
 * Created by admin on 2017/12/11.
 */
/**
 * Created by admin on 2017/9/13.
 */
define([
    "helpers/network",
    "models/user",
    "views/modules/popup",
    "views/modules/form",
    "views/modules/table",
    "views/modules/pager",
    "helpers/util",
    "libs/md5",
    "libs/editor/ueditor.all"
], function (Network, ModelUser, PopupView, CommonForm, CommonTable, CommonPager, Util, Md5) {

    var TYPE = "Info";
    var id = "";
    var windowsId = id + "window";
    var rejectWindowId = id + "rejectWindowId";
    var keywordsId = id + "keywordsId";
    var queryPrerequisiteId = id + "queryPrerequisiteId";
    var accountStatusId = id + "accountStatusId";
    var searchFormId = id + "searchForm";
    var dataRangeId = id + "dataRangeId";
    var membershipStatusId = id + "membershipStatusId";
    var quotaStatusId = id + "quotaStatusId";
    var formId = id + "form";
    var checkboxFormId = id + "checkboxForm";
    var selfConductorFormId = id + "selfConductorForm";
    var rZSJConductorFormId = id + "rZSJConductorForm";
    var tableId = id + "table";
    var pagerId = id + "pager";
    var totalCountsId = id + "totalCounts";
    var pageIndex = 1;

    var onTableReady = function (page) {
        if (!page) {
            page = 1;
        }
        var searchForm = $$(searchFormId).getValues();
        var time = searchForm[dataRangeId]; //获取注册时间选择器对象
        var obj = {
            params: {
                keyWord: searchForm[keywordsId] ? searchForm[keywordsId] : undefined,
                startTime: time.start ? time.start : undefined,
                endTime: time.end ? time.end : undefined,
                privileges: searchForm[membershipStatusId] ? searchForm[membershipStatusId].split(",") : undefined,
                // privileges:["No","Vip"],
                statuss: searchForm[accountStatusId] ? searchForm[accountStatusId].split(",") : undefined
            },
            size: 20,
            page: page,
            sort: ["creationTime,desc"]
        };
        ModelUser.newConductorData(1);
        ModelUser.getRebatePlanData();
        ModelUser.getConductorData({params: {statuss: ["Enable"], bizStatuss: ["Online", "Working", "Offline"], qualificationStatuss: ["ConfirmedApprove"]}, all: true});
        Network.ajax("/UserView.queryAll.query", obj, function (ret) {
            $$(tableId).clearAll();
            $$(tableId).parse(ret.data.content);
            CommonPager.refreshPager(page, ret.data.totalPages);
            $$(totalCountsId).setValue(ret.data.totalElements + "条数据, 共" + ret.data.totalPages + "页");
        });
        pageIndex = page ? page : 1
    };

    var onSubmit = function (oldItem) {
        if (!$$(formId).validate()) {
            webix.message("信息填写有误, 请仔细录入...");
            return
        }
        var itemValues = $$(formId).getValues();
        var ajaxUrl = itemValues.id ? "/UserTransactor.updateUser.command" : "/UserTransactor.createUser.command"
        if (itemValues["privilege"].id == "No") {
            itemValues["privilege"] = []
            delete itemValues.extensionPlan;
        }
        else if (itemValues["privilege"].id == "Vip") {
            itemValues["privilege"] = [itemValues["privilege"].id]
            itemValues["privilegeVipExpireTime"] = Util.getFormattedDateTime("yyyy-MM-dd 23:59:59", itemValues["privilegeVipExpireTime"])
        } else if (itemValues["privilege"].id == "Promotion") {
            itemValues["promotionRebateRate"] = itemValues["promotionRebateRate"] * 100
            itemValues["privilege"] = [itemValues["privilege"].id]
            itemValues.extensionPlan = itemValues.extensionPlan.id;
        }
        // itemValues["conductorId"] = [itemValues["conductorId"].id]
        var obj = {data: itemValues};

        //修改时privilege值获取oldItem数据
        if(itemValues.id){
            obj.data.privilege = oldItem.privilege;
        }
        Network.ajax(ajaxUrl, obj, function (ret) {
            if (itemValues.password.length < 20) {
                Network.ajax("/UserTransactor.updateUserPassword.command", {data: {id: ret.data, password: Md5(itemValues.password)}})
            }
            closeWindow()
            onTableReady(pageIndex);
            webix.message("操作成功")
        })
    };

    var onResetConductor = function (ids) {
        var itemValues = $$(checkboxFormId).getValues()
        //自营彩店
        if (itemValues.gr1xForm == "Self") {
            var selfConductorFormValues = $$(selfConductorFormId).getValues();
            console.log("自营彩店：", selfConductorFormValues)
            itemValues = _.assign(itemValues, selfConductorFormValues);
        } else {
            //第三方彩店
            var rZSJConductorFormValues = $$(rZSJConductorFormId).getValues();
            console.log("第三方彩店：", rZSJConductorFormValues)
            itemValues = _.assign(itemValues, rZSJConductorFormValues);
        }
        var ticketConductorIds = [];
        var itemValuesSize = itemValues.size;
        itemValues["size"] = "20";
        console.log(itemValuesSize)
        if (itemValues) {
            _.forEach(itemValues, function (value, key) {
                if (value == 1) {
                    ticketConductorIds.push(Number(key))
                }
            })
        }
        console.log(ticketConductorIds)
        if (ticketConductorIds.length == 0) {
            if (itemValues.gr1xForm == "Self") {
                webix.message("自营彩店请至少勾选一个！")
                return
            } else {
                webix.message("第三方彩店请至少勾选一个！")
                return
            }

        }
        if (ticketConductorIds.length == itemValuesSize && itemValues.gr1xForm == "Self") {
            ticketConductorIds = [0]
        }
        console.log(ticketConductorIds)
        var obj = {
            data: {
                ids: ids,
                ticketConductorIds: ticketConductorIds
            }
        }
        Network.ajax("/UserTransactor.batchModificationTicketConductorIds.command", obj, function (ret) {
            closeWindow()
            onTableReady(pageIndex);
            webix.message("操作成功")
        })
    }

    var onWindowReady = function (title,item) {
        if("修改用户" == title){
            $$("privilege").disable();
            $$("formPrivilegeVipExpireTime").disable();
            $$("formMobile").disable();
            $$("formPassword").disable();
            $$("formRealName").disable();
            $$("formIdcard").disable();
        } else {
            $$("extensionPlan").hide();
            $$("privilege").attachEvent("onChange", function (newv, oldv) {
                $$("formPrivilegeVipExpireTime").hide();
                $$("extensionPlan").hide();
                if (newv == "Vip") {
                    $$("formPrivilegeVipExpireTime").show();
                }
                if (newv == "Promotion") {
                    $$("extensionPlan").show();

                }

            });
        }

    };

    var closeWindow = function () {
        if ($$(windowsId)) {
            $$(windowsId).close();
        }
        if ($$(rejectWindowId)) {
            $$(rejectWindowId).close();
        }
    };

    //重置登录密码
    var resetPassword = function (item) {
        if (!item) {
            webix.message("请选择一个要修改的项！");
            return
        }
        var obj = {
            data: {
                id: item.id
            }
        }
        Network.ajax("/UserTransactor.resetPassword.command", obj, function () {
            onTableReady(pageIndex)
            webix.message("操作成功！")
        })
    }

    //状态修改
    var updateStatus = function (item) {
        if (!item) {
            webix.message("请选择一个要修改的项！");
            return
        }
        var ajaxUrl = item.status == "Enable" ? "/UserTransactor.disableUser.command" : "/UserTransactor.enableUser.command"
        var obj = {
            data: {
                id: item.id
            }
        }
        Network.ajax(ajaxUrl, obj, function () {
            onTableReady(pageIndex)
            webix.message("操作成功！")
        })
    }

    var showWindow = function (title, item) {
        item = item || {};
        var privilege = "No"
        if (item.privilege) {
            if (item.privilege.indexOf("Promotion") != -1) {
                privilege = "Promotion"
            } else if (item.privilege.indexOf("Vip") != -1) {
                privilege = "Vip";
            }
        }
        PopupView(windowsId, title, {
            rows: [
                {
                    cols: [
                        {
                            view: "scrollview", scroll: "y", gravity: 0.4, padding: 0,
                            body: {
                                // rows: [
                                //             {
                                view: "form", borderless: true, id: formId,
                                elements: [
                                    {
                                        label: "id", name: "id", view: "text", hidden: true,
                                        required: true, value: item.id || ""
                                    },
                                    CommonForm.genSingleOptionSelector("privilege", "用户类型", ModelUser.membershipStatus, privilege, true),
                                    CommonForm.genSingleOptionSelector("extensionPlan", "推广方案", ModelUser.rebatePlanData, item.extensionPlan ||"planOne", true),
                                    {
                                        label: "到期时间", name: "privilegeVipExpireTime", view: "datepicker",
                                        id: "formPrivilegeVipExpireTime",
                                        format: "%Y-%m-%d 23:59:59",
                                        hidden: privilege == "Vip" ? false : true,
                                        required: true,
                                        value: item.privilegeVipExpireTime || ""
                                    },
                                    {
                                        label: "手机号码", view: "text", name: "mobile",id:"formMobile",
                                        required: true,
                                        value: item.mobile || ""
                                    },
                                    {
                                        label: "密码", view: "text", name: "password",id:"formPassword",
                                        required: true,
                                        type: "password",
                                        value: item.password || ""
                                    },
                                    {
                                        label: "真实姓名", view: "text", name: "realName",id:"formRealName",
                                        required: true,
                                        value: item.realName || ""
                                    },
                                    {
                                        label: "身份证", view: "text", name: "idcard",id:"formIdcard",
                                        required: true,
                                        value: item.idcard || ""
                                    },
                                    // CommonForm.genSingleOptionSelector("conductorId", "所属彩店", ModelUser.conductorData, "" || item.conductorId, true),
                                ]
                            }
                        }
                    ]
                },
                {
                    padding: 5,
                    cols: [{}, {
                        view: "button", label: "提交", width: 90,
                        click: function () {
                            onSubmit(item);
                        }
                    }]
                }
            ]
        }, 600, 570, function () {
            onWindowReady(title,item)
        }, closeWindow);
    };

    var resetConductor = function (title, item) {
        item = item || {};
        var ids = [];
        if (item.length > 1) {
            _.forEach(item, function (each) {
                ids.push(Number(each.id))
            })
        } else {
            ids.push(item.id)
        }
        PopupView(windowsId, title, {
            rows: [
                {
                    cols: [
                        {
                            view: "scrollview", scroll: "y", gravity: 0.4, padding: 0,
                            body: {
                                view: "form", borderless: true, id: checkboxFormId,
                                elements: [
                                    {
                                        rows: [
                                            {
                                                cols: [
                                                    {},
                                                    {
                                                        view: "radio", id: "gr1xForm", name: "gr1xForm", label: "彩店类型：", options: [
                                                            {value: "自营彩店", id: "Self"},
                                                            {value: "第三方彩店", id: "ThirdParty"}
                                                        ],
                                                        value: item.vBelongTo || "ThirdParty",
                                                        on: {
                                                            onChange: function (newv, oldv) {
                                                                ModelUser.showOrHide(newv, selfConductorFormId, rZSJConductorFormId);
                                                            }
                                                        }
                                                    },
                                                    {},
                                                ]
                                            },
                                        ],
                                    },
                                    {
                                        cols: [
                                            {
                                                cols: [
                                                    //自营彩店
                                                    {
                                                        view: "form", borderless: true, id: selfConductorFormId,
                                                        elements: []
                                                    },
                                                ]
                                            },
                                            {
                                                cols: [
                                                    //第三方彩店
                                                    {
                                                        view: "form", borderless: true, id: rZSJConductorFormId, hidden: true,
                                                        elements: []
                                                    }
                                                ]
                                            },
                                        ]
                                    }
                                ]
                            },
                        },
                    ],
                },
                {
                    padding: 5,
                    cols: [{}, {
                        view: "button", label: "提交", width: 90,
                        click: function () {
                            onResetConductor(ids);
                        }
                    }]
                }
            ]
        }, 1024, 600, function () {
            ModelUser.getConductorFormView(selfConductorFormId, item, "selfConductor");
            ModelUser.getConductorFormView(rZSJConductorFormId, item, "rZSJConductor");
            ModelUser.showOrHide(item.vBelongTo, selfConductorFormId, rZSJConductorFormId);
        }, closeWindow);
    };

    var genSearchFormUI = function () {
        return {
            view: "scrollview", scroll: "x",
            body: {
                id: searchFormId, view: "form", css: "toolbar", paddingY: 5, paddingX: 10,
                cols: [
                    {},
                    // {
                    //     id: "static", name: "static", view: "select", width: 100, css: {"text-align": "center"},
                    //     value: "mobile",
                    //     options: ModelUser.userSearchTypes
                    // },
                    CommonForm.genKeywordsUI(keywordsId, "依据用户ID/手机号码/真实姓名/用户名进行查询", onTableReady),
                    CommonForm.genMultiOptionsSelector(membershipStatusId, "会员", ModelUser.membershipStatus, _.map(ModelUser.membershipStatus, 'id').join(",")),
                    CommonForm.genMultiOptionsSelector(accountStatusId, "账号状态", ModelUser.accountStatus, _.map(ModelUser.accountStatus, 'id').join(",")),
                    CommonForm.genDateRageSelectorUI(dataRangeId, "注册时间"),
                    CommonForm.genQueryButtonUI(onTableReady)
                ]
            }
        }
    };

    var genOperationFormUI = function () {
        return {
            view: "scrollview", scroll: "x",
            body: {
                view: "form", css: "toolbar", paddingY: 5, paddingX: 10,
                cols: [
                    {view: "label", label: "操作"},
                    {
                        id: "pauseReceiveOrderBtn", view: "button", label: "财务记录", width: 90,
                        // hidden: Authority.hasNoAuth("GOODS_MODIFY"),
                        click: function () {
                            var item = $$("table").getSelectedItem();
                            if (!item) {
                                webix.message("请选择一个要操作的项！");
                                return
                            }
                            sessionStorage.setItem("USER_SESSION", JSON.stringify({keyWord: item.mobile, mobile: item.mobile}));
                            $$("menu_ui").select('financeMntOfUser')
                        }
                    },
                    {
                        view: "button", label: "创建用户", width: 90,
                        // hidden: Authority.hasNoAuth("GOODS_MODIFY"),
                        click: function () {
                            showWindow("创建用户")
                        }
                    },
                    {
                        view: "button", label: "修改用户", width: 90,
                        hidden: false,
                        click: function () {
                            var item = $$("table").getSelectedItem();
                            if (!item) {
                                webix.message("请选择一个要修改的项！");
                                return
                            }
                            if(item.privilege.indexOf("Promotion") == -1){
                                webix.message("只支持修改区域推广用户。");
                                return;
                            }
                            if(item.privilege.indexOf("Quota") !== -1){
                                webix.message("只支持修改区域推广用户。");
                                return;
                            }
                            showWindow("修改用户", item)
                        }
                    },
                    {
                        view: "button", label: "批量修改出票彩店", width: 120,
                        // hidden: Authority.hasNoAuth("GOODS_MODIFY"),
                        click: function () {
                            var item = $$("table").getSelectedItem();
                            if (!item) {
                                webix.message("请选择一个要修改的项！");
                                return
                            }
                            resetConductor("修改出票彩店", item)
                        }
                    },
                    {
                        view: "button", label: "重置密码", width: 90,
                        // hidden: Authority.hasNoAuth("GOODS_MODIFY"),
                        click: function () {
                            var item = $$("table").getSelectedItem();
                            resetPassword(item)
                        }
                    },
                    {
                        id: "enableShopBtn", view: "button", label: "禁用/启用", width: 90,
                        // hidden: Authority.hasNoAuth("GOODS_MODIFY"),
                        click: function () {
                            var item = $$("table").getSelectedItem();
                            updateStatus(item);
                        }
                    }
                ]
            }
        }
    };

    var genDataTableUI = function () {
        return {
            id: tableId, view: "datatable", resizeColumn: true, select: "row", data: [], multiselect: true,
            complexData: true,
            ready: onTableReady,
            on: {
                onItemClick: function (id) {
                    var item = this.getItem(id);
                    if (item.status === "Disable") {
                        $$("enableShopBtn").define("label", "启用")
                    } else if (item.status === "Enable") {
                        $$("enableShopBtn").define("label", "禁用")
                    }
                    $$('enableShopBtn').refresh();
                }
            },
            columns: [
                {
                    id: "id", header: "ID"
                },
                {
                    id: "nickname", header: "用户昵称", fillspace: true,
                    // template: "#data.remark#"
                },
                {
                    id: "realName", header: "真实姓名", fillspace: true,
                    // template: "#data.remark#"
                },
                {
                    id: "vConductorData", header: "资金对接彩店", fillspace: true,
                    template: function (obj) {
                        var vConductorData = obj.vConductorData;
                        return vConductorData ? vConductorData.name : ""
                    }
                },
                {
                    id: "vTicketConductorDatas", header: "出票彩店", fillspace: true,
                    template: function (obj) {
                        var vTicketConductorDatas = obj.vTicketConductorDatas
                        var vBelongTo = obj.vBelongTo;
                        if (vTicketConductorDatas && vTicketConductorDatas.length > 0) {
                            var names = [];
                            _.forEach(vTicketConductorDatas, function (each) {
                                names.push(each.name)
                            })
                            if (names.length > 1) {
                                if (vBelongTo == "Self") {
                                    return "自营彩店共：" + names.length + "家"
                                } else {
                                    return "第三方彩店共：" + names.length + "家"
                                }
                            } else {
                                if (vBelongTo == "Self") {
                                    return "自营彩店：" + names.join(",")
                                } else {
                                    return "第三方彩店：" + names.join(",")
                                }
                            }
                        } else {
                            return "所有店铺都能接单"
                        }
                    }
                },
                {
                    id: "mobile", header: "手机号", fillspace: true,
                    // template: "#data.remark#"
                },
                {
                    id: "capital", header: "余额(元)", fillspace: true,
                    template: function (obj) {
                        return obj.balance ? Number(obj.balance).toCurrency() : "0".toCurrency()
                    }
                },
                {
                    id: "vPrivilege", header: "用户类别", fillspace: true,
                    template: function (obj) {
                        var privilege = obj.privilege;
                        var extensionPlan = obj.extensionPlan;
                        if (privilege.length > 0) {
                            var planName = "";
                            _.forEach(ModelUser.rebatePlanData, function (each) {
                                    if(each.id==extensionPlan){
                                        planName = each.value;
                                        return true;
                                    }
                            });
                            var s1 = "";
                            var s2 = "";
                            if (privilege.indexOf("Vip") !== -1) {
                                s1 += "VIP";
                            }
                            if(privilege.indexOf("Quota") !== -1){
                                s1 += "配额"
                            }
                            if(privilege.indexOf("Promotion") !== -1){
                                s1 += "区域推广"
                                s2 = "("+planName+")"
                            }
                            s1 += "用户" + s2;
                            return s1;

                        } else {
                            return "普通用户"
                        }
                    }
                },
                {
                    id: "privilegeVipExpireTime", header: "VIP到期日", fillspace: true,
                    // template: "#data.remark#"
                },
                // {
                //     id: "quotaBorrowed", header: "配额(剩/总)", fillspace: true,
                //     template: function (obj) {
                //          return Number(obj.quota/100).toString() +"/"+ Number(obj.quotaUpperLimit/100).toString()
                //     }
                // },
                {
                    id: "vStatusText", header: "账号状态", fillspace: true,
                    // template: "#data.remark#"
                },
                {
                    id: "signupTime", header: "注册时间", fillspace: true,
                    // template: "#data.remark#"
                }
            ]
        }
    };

    var genFooterUI = function () {
        return {
            cols: [
                CommonPager.genPagerUI(pagerId, onTableReady),
                CommonPager.genTotalCountsUI(totalCountsId), {}
            ]
        }
    };

    return {
        $ui: {
            padding: 10,
            rows: [
                genSearchFormUI(),
                genOperationFormUI(),
                genDataTableUI(),
                genFooterUI()
            ]
        }
    };

});